package com.yanqu.road.server.cmd.activity.climbtower;

import com.yanqu.road.entity.activity.climbtower.UserClimbTowerTopClimbRecord;
import com.yanqu.road.logic.bussiness.player.ClimbTowerActivityBussiness;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.ClimbTowerProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.climbtower.ClimbTowerModule;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.pb.ClimbTowerActivityPb;
import com.yanqu.road.server.protocol.Protocol;


@Cmd(code = Protocol.S_CLIMB_TOWER_TOP_CLIMB_CROSS_RESP, desc = "新幻境爬塔跨服返回")
public class ClimbTowerTopClimbCrossRespCmd extends AbstractCommand {
    private ClimbTowerProto.CrossClimbTowerTopClimbRespMsg crossMsg;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        crossMsg = ClimbTowerProto.CrossClimbTowerTopClimbRespMsg.parseFrom(packet.getBytes());
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        ClimbTowerProto.ClimbTowerTopClimbRespMsg settleMsg = crossMsg.getRetClient();
        ret = settleMsg.getRet();
        if(0 == ret) {
            UserClimbTowerTopClimbRecord record = null;
            if (crossMsg.getEnemyUserId() > 0) {
                record = ClimbTowerActivityPb.buildTopClimbRecord(crossMsg);
            }

            if (crossMsg.getIsAttack()) {//结算奖励和历史最高层
                player.getModule(ClimbTowerModule.class).topCellClimbSettle(crossMsg, record);
                AutoLogMgr.add(ClimbTowerActivityPb.buildLogClimbTowerTopFight(crossMsg));
            }

            if (!crossMsg.getIsAttack() && record != null) {
                //增加被攻击日志
                if (null != player) {
                    player.getModule(ClimbTowerModule.class).addTopCellClimbRecord(record);
                    player.getModule(ClimbTowerModule.class).getUserData().setTopCellNum(record.getNewCellNum());
                    if (record.getOldCellNum() > record.getNewCellNum()) {
                        player.sendPacket(Protocol.U_CLIMB_TOWER_TOP_LAST_DEFEATED, ClimbTowerActivityPb.buildLastDefeatMsg(record));
                    }
                } else {
                    ClimbTowerActivityBussiness.addUserClimbTowerTopClimbRecord(record);
                }
            }
        }
    }

    @Override
    public void sendData(GamePlayer player) {
        if (null != player && crossMsg.getIsAttack()) {
            player.sendPacket(Protocol.U_CLIMB_TOWER_TOP_CLIMB, crossMsg.getRetClient().toBuilder());
        }
    }
}
